var addressObj = {};
var isLastLevel = false;
(function (factory) {
    if (typeof define === "function" && (define.amd || define.cmd) && !jQuery) {
        // AMD或CMD
        define(["jquery"], factory);
    } else if (typeof module === 'object' && module.exports) {
        // Node/CommonJS
        module.exports = function (root, jQuery) {
            if (jQuery === undefined) {
                if (typeof window !== 'undefined') {
                    jQuery = require('jquery');
                } else {
                    jQuery = require('jquery')(root);
                }
            }
            factory(jQuery);
            return jQuery;
        };
    } else {
        //Browser globals
        factory(jQuery);
    }
}
(function ($) {
      list_new=[];
    //配置参数
     defaults = {
        param:'',
        provinceName: '请选择省市', //省份名字
        provinceCode: '', //省份code
        provinceId: '',//省份id
        cityName: '',//城市名字
        cityCode: '',//城市code
        cityId: '',//城市id
        width:'290px',
        level:'',
    };
    var Address = function (element, options) {
        //全局变量
            opts = options, //配置
            $document = $(document),
            $obj = $(element), //容器
            _name = $obj.attr('class')+'_',    // div的class用来给元素命名
            areaShow = true;  //是否初始化

        //绑定事件
        this.eventBind = function () {
            var that = this;
            $obj.on('click', '.inp_area', function () {
                if($(this).attr("showStatus")){
                  $(this).attr("showStatus","showStatus");
                  $('.' + _name + 'area_list').addClass('hide');
                } else {
                  $(this).removeAttr("showStatus");
                  $('.' + _name + 'area_list').removeClass('hide');
                }
                if(areaShow){
                    that.initProvince(opts.provinceName)
                }
                areaShow = !areaShow;
            })
            $obj.on('click', '.area_list li', function () {
                var level = Number($(this).attr('data-level'));
                var code = $(this).attr('data-code');
                var addressId = $(this).attr('data-id');
                var warehouseCode = $(this).attr('data-warehouse');
                isLastLevel = false;
                that.getArea(level,code,this.innerHTML,'noTab',addressId,warehouseCode)
            })
            $obj.on('click', '.area_list .tab span', function () {
                var level = $(this).attr('data-level')
                that.getArea(level,'','','tab')
            })
            $obj.on('click', '.area_list .close', function () {
                that.isAreaHide(1);
            })
        };

        //初始化省份
        this.initProvince = function (province) {
            $.ajax({
                url: root.sroreinter.getLowerAddress,
                contentType: "application/x-www-form-urlencoded",
                type: 'post',
                cache: false,
                data: {},
                success: function(data, status, response){
                    if(data.errorCode == 0){
                        $('.'+_name+'area_tab1').html(province||'请选择');
                        $('.'+_name+'area_tab1').addClass('curr');
                        $('.'+_name+'area_tab2').removeClass('curr');
                        $('.'+_name+'area_list .list').empty()
                        for(var i = 0 , len = data.list.length ; i < len ; i++){
                            var area = data.list[i];
                            var html = '';
                            html +='<li style="cursor:pointer;" data-level="'+area.level+'" data-code="'+area.code+'" data-id="'+area.address_id+'" data-warehouse="' + area.warehouse_code + '" title="' + area.name + '">'+area.name+'</li>'
                            $('.'+_name+'area_list .list').append(html);
                        }
                    }
                },
                error: function (xhr, type, errorThrown) {
                    alert('通讯错误，请重试。');
                }
            });
        }

        //获取地址列表！！！
        this.getArea = function(level, parentCode, e, isTab, addressId, warehouseCode) {
            var that = this;
            switch (level){
                case '102':
                    parentCode = opts.parentCode2;
                    e = opts.goName2;
                    break;
            }
            var nextlevel = String(Number(level) + 1);
            if (isTab == "tab") {
                var nextlevel = String(level);
                if(level == "101"){
                    opts.cityName = "";
                    areaShow = !areaShow;
                }
                else if(level == "102"){
                    opts.areaName = "";
  
                    opts.streetName = "";
                    areaShow = !areaShow;
                }
                else if(level == "103"){
                    opts.streetName = "";
                    areaShow = !areaShow;
                }
            }
            else if (isTab == "noTab") {
                if(level == '101'){
                    opts.provinceName = e;
                    opts.cityName = "";
                    opts.provinceCode = parentCode;
                    opts.provinceId = addressId;
                    opts.cityCode = '';
                    opts.cityId = '';
                }
            }
            if (!(nextlevel == "105")) {
              list_new.push(nextlevel)
              if(nextlevel <=103){
                $.ajax({
                  url: root.sroreinter.getLowerAddress,
                  contentType: "application/x-www-form-urlencoded",
                  type: 'post',
                  cache: false,
                  data: {level: nextlevel,
                    parentCode: parentCode,
                  },
                  success: function(data, status, response){
                    if (data.errorCode == 0) {
                      var areas = data.list;
                      $('.' + _name + 'area_list .list').empty();
                      for(var i = 0 , len = areas.length ; i < len ; i++){
                        var area = areas[i];
                        var html = '';
                        html +='<li style="cursor:pointer;" data-level="'+area.level+'" data-code="'+area.code+'" data-id="'+area.address_id+'"  title="' + area.name + '">'+area.name+'</li>'
                        $('.' + _name + 'area_list .list').append(html);
                      }
                      $('.' + _name + 'area_tab1').addClass('curr');
                      $('.' + _name + 'area_tab2').removeClass('curr');
                      if (nextlevel == '102') {
                        $('.' + _name + 'area_tab2').removeClass('hide');
                        if (isTab == "noTab") {
                          if(areas.length<=0){
                            areaShow = areaShow;
                            that.isAreaHide()
                            return false;
                          }else{
                            $('.' + _name + 'area_tab2').html('请选择');
                            areaShow = !areaShow;
                          }
                        }
                        $('.' + _name + 'area_tab1').removeClass('curr');
                        $('.' + _name + 'area_tab2').addClass('curr');
                        $('.' + _name + 'area_tab1').html(e);
                        opts.parentCode2 = parentCode;
                        opts.goName2 = e;
                     
                      } else if (nextlevel == '103') {
                        areaShow = areaShow;
                        if (isTab == "noTab") {
                          opts.cityName = e;
                          $('#' + _name + 'provinceName').html(opts.provinceName);
                          $('#' + _name + 'cityName').html(opts.cityName)
                          opts.cityCode = parentCode;
                          opts.cityId = addressId;
                          areaShow = areaShow;
                        }
                        $('.' + _name + 'area_tab1').removeClass('curr');
                        $('.' + _name + 'area_tab2').removeClass('curr');
                        $('.' + _name + 'area_tab2').html(e);
                        opts.parentCode3 = parentCode;
                        opts.goName3 = e;
                        that.isAreaHide()
                        return false;
                      }
                    }
                  },
                  error: function (xhr, type, errorThrown) {
                    alert('通讯错误，请重试。');
                  }
                });
              }
            }
            addressObj[opts.param]=opts
        }
        // 收起地址列表
        this.isAreaHide = function(isT) {
            $('.area_list').addClass('hide');
            if(!isT){
              isLastLevel = true;
            }
        }
        //初始化
        this.init = function () {
            var html = '<div class="area_box ' + _name + 'area_box" style="position:relative;width:' + opts.width + '">'
            html +='<div class="inp_area ' + _name + 'inp_area" style="margin-top: 0;width:' + opts.width + '">'
            html += '<div class="inp_area_box" style="width:' + opts.width + '">'
            html += '<span id="' + _name + 'provinceName" class="provinceName">'+opts.provinceName +'</span>'
            html += '<span id="' + _name + 'cityName" class="cityName">'+opts.cityName+'</span>'
            html += '</div>'
            html += '</div>'
            html += '<div class="area_list ' + _name + 'area_list hide">'
            html += '<div class="tab clearfix">'
            html += '<span class="' + _name + 'area_tab1 curr" data-level="101">'+opts.provinceName+'</span>'
          if (opts.areaName != ''){
            if (opts.streetName != '') {
              html += '<span class="' + _name + 'area_tab2" data-level="102">'+opts.cityName+'</span>'
            } else {
              html += '<span class="' + _name + 'area_tab2" data-level="102">'+opts.cityName+'</span>'
            }
          } else if (opts.areaName == ''){
            html += '<span class="' + _name + 'area_tab2 hide" data-level="102">请选择</span>'
          }
            html += '</div>'
            html += '<a class="close">关闭</a>'
            html += '<ul class="list clearfix" style="min-width: 350px;">'
            html += '</ul>'
            html += '</div>'
            html += '</div>'
            $obj.html(html)
            this.eventBind();
        };
        this.init();
    };

    $.fn.address = function (parameter) {
        var options = $.extend({}, defaults, parameter);
        return this.each(function () {
            var address = new Address(this, options);
        });
    };

}));
